<template>
  <view class="Members">
    <scroll-view scroll-x class="bg-white nav">
      <view class="flex text-center">
        <view class="cu-item flex-sub" :class="item.key===curTab?'text-orange cur':''" v-for="item in tabs" :key="item.key" @tap="tabSelect(item.key)">
          {{ item.name }}
        </view>
      </view>
    </scroll-view>

    <scroll-view :scroll-y="true" class="ScroViewClass" enable-back-to-top="true">

      <template v-if="curTab === 4">
        <view class="cu-form-group" >
          <view class="title">学生姓名</view>
          <input placeholder="请输入学生姓名" @input="onStudentNameConfirm">
          <!--        <button class='cu-btn bg-blue shadow' @tap="userIdCheck">查询</button>-->
        </view>

        <view class="cu-form-group" >
          <view class="title">学生学号</view>
          <input placeholder="请输入学生学号" @input="onStudentNoConfirm">
          <!--        <button class='cu-btn bg-blue shadow' @tap="userIdCheck">查询</button>-->
        </view>
      </template>

      <template v-else-if="curTab === 3">
        <view class="cu-form-group" >
          <view class="title">教师姓名</view>
          <input placeholder="请输入教师姓名" @input="onTeacherNameConfirm">
          <!--        <button class='cu-btn bg-blue shadow' @tap="userIdCheck">查询</button>-->
        </view>

        <view class="cu-form-group" >
          <view class="title">教师编号</view>
          <input placeholder="请输入教师编号" @input="onTeacherNoConfirm">
          <!--        <button class='cu-btn bg-blue shadow' @tap="userIdCheck">查询</button>-->
        </view>
      </template>

      <template v-else-if="curTab === 2">
        <view class="cu-form-group" >
          <view class="title">管理员姓名</view>
          <input placeholder="请输入管理员姓名" @input="onTeacherNameConfirm">
          <!--        <button class='cu-btn bg-blue shadow' @tap="userIdCheck">查询</button>-->
        </view>

        <view class="cu-form-group" >
          <view class="title">管理员编号</view>
          <input placeholder="请输入管理员编号" @input="onTeacherNoConfirm">
          <!--        <button class='cu-btn bg-blue shadow' @tap="userIdCheck">查询</button>-->
        </view>
      </template>

      <view class="cu-form-group">
        <view class="title">是否启用</view>
        <radio-group @change="changeStatus">
          <view class="flex">
            <view>
              <label class="text-sm">是</label>
              <radio
                  :class="['radio','blue',curSelectStatus === '1' ? 'checked' : '']"
                  :checked="curSelectStatus === '1'"
                  value="1"
                  style="transform: scale(0.8)"
              >
              </radio>

              <label class="text-sm">否</label>
              <radio
                  :class="['radio','blue',curSelectStatus === '0' ? 'checked' : '']"
                  :checked="curSelectStatus === '0'"
                  value="0"
                  style="transform: scale(0.8)"
              >
              </radio>
            </view>
          </view>
        </radio-group>
      </view>

      <view class="bg-white padding-sm">
        <view class="grid margin-bottom text-center text-sm text-bold col-5">
          <view class="table-title-bg padding flex-sub">编号</view>
          <view class="table-title-bg padding flex-twice">用户名</view>
          <view class="table-title-bg padding flex-twice">手机号</view>
          <view class="table-title-bg padding flex-twice" v-if="curTab !== 4">专业</view>
          <view class="table-title-bg padding flex-sub">状态</view>
        </view>

        <view class="table-item grid margin-bottom text-center col-5 text-sm" v-for="item in memberList" :key="item.CUSER_ID" @tap="toDetail(item.CUSER_ID)" @longpress="onItemLongPress(item.CUSER_ID)">
          <view class="padding flex-sub">{{item.CUSER_ID}}</view>
          <view class="padding flex-twice text-blue" style="text-decoration: underline">{{item.USERNAME}}</view>
          <view class="padding flex-twice" style="word-break:break-all;">{{item.PHONENO}}</view>
          <view class="padding flex-twice" v-if="curTab !== 4">{{item.MAJOR_NAME}}</view>
          <view class="padding flex-sub">{{item.STATENR}}</view>
        </view>

        <view v-if="memberList.length === 0" class="text-sm text-center">-- 暂无数据 --</view>
      </view>

      <view class="cu-form-group" v-if="totalPage > 0">
        <view class="title" @tap="firstPage()"><text class="check-info-btn">首页</text></view>
        <view class="title" @tap="lastPage()"><text class="check-info-btn">上一页</text></view>
        <view class="title">{{page}}/{{totalPage}}</view>
        <view class="title" @tap="nextPage()"><text class="check-info-btn">下一页</text></view>
        <view class="title" @tap="endPage()"><text class="check-info-btn">尾页</text></view>
      </view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import {useStore} from "vuex";
import {useMembers} from "./useMembers";
import {usePagination} from "../../utils/usePagination";
import {computed, onMounted, ref} from "vue";
import {onPullDownRefresh} from "@dcloudio/uni-app";
import {getMemberDetail, modifyUserStatus} from "../../api/manage";
import {useLogin} from "../account/useLogin";

const {memberList, initMemberList, total} = useMembers()
const inputStudentName = ref('')

function onStudentNameConfirm(e: any) {
  inputStudentName.value = e.detail.value
  page.value = 1
}

const curSelectStatus = ref<'1' | '0'>('1')
async function changeStatus(e: any){
  curSelectStatus.value = e.detail.value
  page.value = 1
  // await initData()
}

// onPullDownRefresh(() => {
//   inputStudentName.value = ''
//   page.value = 1
//   // await initData()
//   uni.stopPullDownRefresh()
// })

const tabs = [
  {
    key: 4,
    name: '学生'
  },
  {
    key: 3,
    name: '教师'
  },
  {
    key: 2,
    name: '管理员'
  }
]

const inputTeacherName = ref('')
function onTeacherNameConfirm(e: any){
  inputTeacherName.value = e.detail.value
  page.value = 1
}

const inputStudentNo = ref('')
function onStudentNoConfirm(e: any){
  inputStudentNo.value = e.detail.value
  page.value = 1
}

const inputTeacherNo = ref('')
function onTeacherNoConfirm(e: any){
  inputTeacherNo.value = e.detail.value
  page.value = 1
}

const curTab = ref(4)
async function tabSelect(key: number){
  if (curTab.value === key){
    return
  }
  curTab.value = key
  page.value = 1
  clearSearchParams()
  // await initData()
}

const pageSize = 20
const {page} = usePagination({
  page: 1,
  pageSize,
  onPageChange: initMemberList,
  startReachBottom: false,
  args: ref({
    STUDENTNAME: inputStudentName,
    STUDENTNO: inputStudentNo,
    TEACHERNAME: inputTeacherName,
    TEACHERNO: inputTeacherNo,
    roleId: curTab,
    state: curSelectStatus
  })
})
const totalPage = computed(() => parseInt(String(total.value / pageSize)) + (total.value % pageSize === 0 ? 0 : 1))
function firstPage() {
  page.value = 1
}

function lastPage(){
  if (page.value > 1){
    page.value--
  }
}

function nextPage() {
  if (page.value < totalPage.value){
    page.value++
  }
}

function endPage(){
  page.value = totalPage.value
}

function clearSearchParams(){
  curSelectStatus.value = '1'
  inputStudentName.value = ''
  inputStudentNo.value = ''
  inputTeacherName.value = ''
  inputTeacherNo.value = ''
}

onPullDownRefresh(() => {
  clearSearchParams()
  page.value = -1
  page.value = 1
  uni.stopPullDownRefresh()
})
const {state} = useStore()
async function toDetail(id: number){
  try {
    const res = await getMemberDetail({
      CUSER_ID: id + '',
      OPERATOR_ID: state.user.userInfo.CUSER_ID
    })
    if (res.ERROR[0].errcode == '0'){
      if (res.DAT.length > 0){
        uni.navigateTo({
          url: `/pages/manage/memberDetail?info=${encodeURIComponent(JSON.stringify(res.DAT[0]))}`
        })
      }else {
        uni.showToast({
          title: '该用户尚未完善资料',
          icon: 'none',
          mask: true
        })
      }
    }else {
      uni.showToast({
        title: res.ERROR[0].error,
        icon: 'none',
        mask: true
      })
    }
  }catch (err) {
    uni.showToast({
      title: '获取报名表失败',
      icon: 'error',
      mask: true
    })
  }
}

const {ROLE_ID} = useLogin()
function onItemLongPress(id: number){
  if (ROLE_ID.value != '2'){
    return
  }
  uni.showModal({
    title: '提示',
    content: `是否${curSelectStatus.value === '1' ? '停' : '启'}用当前用户？`,
    success: async ({confirm}) => {
      if (confirm){
        try {
          const res = await modifyUserStatus({
            CUSER_IDS: id + '',
            STATE: curSelectStatus.value === '1' ? '0' : '1',
            OPERATOR_ID: state.user.userInfo.CUSER_ID
          })

          if (res.ERROR[0].errcode == '0'){
            uni.showToast({
              title: '修改成功',
              icon: 'success',
              mask: true
            })

            setTimeout(() => {
              const oldPage = page.value
              page.value = -1
              page.value = oldPage
            },500)
          }else {
            uni.showToast({
              title: res.ERROR[0].error,
              icon: 'none',
              mask: true
            })
          }
        }catch (err) {
          uni.showToast({
            title: '修改错误',
            icon: 'error',
            mask: true
          })
        }

      }
    }
  })
}

onMounted(() => {
  uni.$on('updateRole',() => {
    const oldPage = page.value
    page.value = -1
    page.value = oldPage
  })
})
</script>

<style scoped lang="scss">
.Members{

}
.cu-form-group .title {
  min-width: calc(4em + 15px);
}
.check-info-btn {
  color: #01AAED;
}
.ScroViewClass {
  min-height: 300rpx;
  padding-bottom: constant(safe-area-inset-bottom);  ///兼容 IOS<11.2/
  padding-bottom: env(safe-area-inset-bottom);  ///兼容 IOS>11.2/
}
.table-title-bg {
  background-color: #DDDDDD;
}

.table-item:active{
  background-color: #DDDDDD;
}
</style>
